package com.boc.langxiang.ui.activity.shop;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.boc.langxiang.App;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.shop.ShoppingCarContract;
import com.boc.langxiang.contract.shop.ShoppingCarControlContract;
import com.boc.langxiang.entity.bean.MultipleItem;
import com.boc.langxiang.entity.bean.ShoppingCarInfo;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.entity.response.ShoppingCarContent;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.presenter.shop.ShoppingCarControlPresenter;
import com.boc.langxiang.presenter.shop.ShoppingCarListPresenter;
import com.boc.langxiang.ui.activity.BaseToolBarActivity;
import com.boc.langxiang.ui.dialog.CustomAlertDialog;
import com.boc.langxiang.ui.view.NumberPicker;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.animation.AlphaInAnimation;
import com.jakewharton.rxbinding.view.RxView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;


/**
 * 购物车
 */
public class ShoppingCarActivity extends BaseToolBarActivity implements View.OnClickListener, ShoppingCarContract.View {

    RecyclerView productsRecycler;

    RecyclerView salonRecycler;

    @BindView(R.id.select_all_iv)
    ImageView selectAllIv;
    @BindView(R.id.select_all_layout)
    LinearLayout selectAllLayout;
    @BindView(R.id.submit_products)
    RelativeLayout submitProducts;
    @BindView(R.id.bottom_bar)
    RelativeLayout bottomBar;
    @BindView(R.id.total_price_tv)
    TextView totalPriceTv;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.total_amount_layout)
    LinearLayout totalAmountLayout;
    @BindView(R.id.submit_tv)
    TextView submitTv;
    private boolean isEditing = false;

    private boolean isSelectall = false;

    private ShoppingCarAdapter productsAdapter;
    private ShoppingCarAdapter salonAdapter;

    private MultiAdapter multiAdapter;

    private View emptyView;

    private ShoppingCarContract.Presenter mPresenter;

    private double mTotalPrice = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_car);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        initAdapter();
        emptyView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);

        multiAdapter.setEmptyView(emptyView);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(multiAdapter);

//        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
//        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
//        productsRecycler.setLayoutManager(layoutManager1);
//
//        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
//        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
//        salonRecycler.setLayoutManager(layoutManager2);
//
//        productsAdapter = new ShoppingCarAdapter(new ArrayList<ShoppingCarInfo>());
//        salonAdapter = new ShoppingCarAdapter(new ArrayList<ShoppingCarInfo>());
//
//
//        productsRecycler.setAdapter(productsAdapter);
//        salonRecycler.setAdapter(salonAdapter);

        selectAllLayout.setOnClickListener(this);
        submitProducts.setOnClickListener(this);


    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initAdapter() {
        productsAdapter = new ShoppingCarAdapter(new ArrayList<ShoppingCarInfo>());
        salonAdapter = new ShoppingCarAdapter(new ArrayList<ShoppingCarInfo>());

        productsAdapter.openLoadAnimation(new AlphaInAnimation());
        salonAdapter.openLoadAnimation(new AlphaInAnimation());
        multiAdapter = new MultiAdapter(mContext, new ArrayList<MultipleItem>());
        multiAdapter.openLoadAnimation(new AlphaInAnimation());
    }

    private void initData() {
        mPresenter = new ShoppingCarListPresenter(this);
        mPresenter.getList();
    }

    @Override
    protected boolean isSetTypeFace() {
        return true;
    }

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        setToolBarTitle("购物车");
        toolbar.setNavigationIcon(R.drawable.icon_return_black);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
                if (isEditing) {
                    isEditing = false;
                    item.setTitle("编辑");
                    submitTv.setText("结算");
                    totalAmountLayout.setVisibility(View.VISIBLE);
                } else {
                    isEditing = true;
                    item.setTitle("完成");
                    submitTv.setText("删除");
                    totalAmountLayout.setVisibility(View.GONE);
                }
                productsAdapter.notifyDataSetChanged();
                salonAdapter.notifyDataSetChanged();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_edit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_all_layout:
                selectAll();
                break;

            case R.id.submit_products:
                if (isEditing) {
                    deleteSelectedItem();
                } else {
//                    AlertDialog alertDialog = new AlertDialog.Builder(mContext)
//                            .setCancelable(true)
//                            .setMessage("商品运费及安装费用需另行支付")
//                            .setOnCancelListener(new DialogInterface.OnCancelListener() {
//                                @Override
//                                public void onCancel(DialogInterface dialog) {
//                                }
//                            })
//                            .setPositiveButton("知道啦", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    submitOrder();
//                                }
//                            })
//                            .create();
//                    alertDialog.show();

                    View cancelView = View.inflate(mContext, R.layout.popwindow_orders_cancel, null);
                    TextView message = (TextView) cancelView.findViewById(R.id.message);
                    TextView giveup = (TextView) cancelView.findViewById(R.id.atv_me_orders_giveup);
                    TextView sure = (TextView) cancelView.findViewById(R.id.atv_me_orders_sure);

                    message.setText("商品运费及安装费用需另行支付");
                    sure.setText("知道啦");
                    final PopupWindow cancelPopupWindow = new PopupWindow(cancelView, (int) (App.getInstance().getResources().getDisplayMetrics().widthPixels * 0.8), LinearLayout.LayoutParams.WRAP_CONTENT);
                    cancelPopupWindow.setAnimationStyle(R.style.me_pop_anim_center_style);
                    cancelPopupWindow.setFocusable(true);
                    cancelPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    cancelPopupWindow.setOutsideTouchable(true);
                    cancelPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            setBackgroundAlpht(1f);
                        }
                    });
                    RxView.clicks(cancelPopupWindow.getContentView().findViewById(R.id.atv_me_orders_sure)).throttleFirst(2000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Action1<Void>() {
                                @Override
                                public void call(Void aVoid) {
                                    cancelPopupWindow.dismiss();
                                    submitOrder();
                                }
                            });
                    RxView.clicks(cancelPopupWindow.getContentView().findViewById(R.id.atv_me_orders_giveup)).throttleFirst(2000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Action1<Void>() {
                                @Override
                                public void call(Void aVoid) {
                                    cancelPopupWindow.dismiss();
                                }
                            });
                    cancelPopupWindow.showAtLocation(cancelView, Gravity.CENTER, 0, 0);
                    setBackgroundAlpht(0.5f);
                }
                break;
        }
    }

    private void setBackgroundAlpht(float value) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha = value;
        getWindow().setAttributes(attributes);
    }

    private void deleteSelectedItem() {
        final List<ShoppingCarInfo> shoppingCarInfos = new ArrayList<>();
        final List<Integer> productsPositions = new ArrayList<>();
        for (int i = 0; i < productsAdapter.getData().size(); i++) {
            ShoppingCarInfo info = productsAdapter.getData().get(i);
            if (info.isSelected()) {
                shoppingCarInfos.add(info);
                productsPositions.add(i);
            }
        }

        final List<Integer> salonPositions = new ArrayList<>();
        for (int i = 0; i < salonAdapter.getData().size(); i++) {
            ShoppingCarInfo info = salonAdapter.getData().get(i);
            if (info.isSelected()) {
                shoppingCarInfos.add(info);
                salonPositions.add(i);
            }
        }

        String ids = "";
        if (shoppingCarInfos.size() > 0) {
            for (int i = 0; i < shoppingCarInfos.size(); i++) {
                if (i == 0) {
                    ids += shoppingCarInfos.get(i).getId();
                } else {
                    ids += "," + shoppingCarInfos.get(i).getId();
                }
            }
        }

        if (ids.length() > 0) {
            final String finalIds = ids;
            showCustomAlertDialog("提示", "您确认要删除所选的项目吗", "取消", "删除", new CustomAlertDialog.CustomAlertDialogClickListener() {
                @Override
                public void onPositiveButtonClick() {
                    new ShoppingCarControlPresenter(new ShoppingCarControlContract.View() {
                        @Override
                        public void onSuccess() {
                            Iterator<ShoppingCarInfo> productIterator = productsAdapter.getData().iterator();
                            while (productIterator.hasNext()) {
                                ShoppingCarInfo info = productIterator.next();
                                if (shoppingCarInfos.contains(info)) {
                                    productIterator.remove();
                                }
                                productsAdapter.notifyDataSetChanged();
                            }

                            Iterator<ShoppingCarInfo> salonIterator = salonAdapter.getData().iterator();
                            while (salonIterator.hasNext()) {
                                ShoppingCarInfo info = salonIterator.next();
                                if (shoppingCarInfos.contains(info)) {
                                    salonIterator.remove();
                                }
                                salonAdapter.notifyDataSetChanged();
                            }

                            setupTotalPrice();
                        }

                        @Override
                        public void showLoading() {
                            showProgressDialog("操作中，请稍候...");
                        }

                        @Override
                        public void hideLoading() {
                            hideDialog();
                        }

                        @Override
                        public void onError(String code, String msg) {
                            T.showShort(mContext, msg);
                        }
                    }).deleteItem(finalIds);
                }

                @Override
                public void onNegativeButtonClick() {

                }
            });
        }
    }

    private void submitOrder() {
        List<String> idList = new ArrayList<>();
        if (productsAdapter.getData().size() > 0) {
            for (int i = 0; i < productsAdapter.getData().size(); i++) {
                if (productsAdapter.getData().get(i).isSelected()) {
                    idList.add(productsAdapter.getData().get(i).getId());
                }
            }
        }

        if (salonAdapter.getData().size() > 0) {
            for (int i = 0; i < salonAdapter.getData().size(); i++) {
                if (salonAdapter.getData().get(i).isSelected()) {
                    idList.add(salonAdapter.getData().get(i).getId());
                }
            }
        }

        if (idList.size() > 0) {
            String ids = "";
            for (int i = 0; i < idList.size(); i++) {
                if (i == 0) {
                    ids += idList.get(i);
                } else {
                    ids += "," + idList.get(i);
                }
            }
            Intent i = new Intent(mContext, OrderConfirmActivity.class);
            i.putExtra("ids", ids);
            startActivity(i);

        } else {
            T.showShort(mContext, "请选择要结算的商品");
        }


    }

    private void selectAll() {
        if (isSelectall) {
            isSelectall = false;
            selectAllIv.setImageResource(R.drawable.icon_checkbox_address_normal);
        } else {
            isSelectall = true;
            selectAllIv.setImageResource(R.drawable.icon_checkbox_address_checked);
        }
        selectAllData();
    }

    private void selectAllData() {
        for (int i = 0; i < productsAdapter.getData().size(); i++) {
            productsAdapter.getData().get(i).setSelected(isSelectall);
        }
        productsAdapter.notifyDataSetChanged();

        for (int i = 0; i < salonAdapter.getData().size(); i++) {
            salonAdapter.getData().get(i).setSelected(isSelectall);
        }
        salonAdapter.notifyDataSetChanged();

        setupTotalPrice();
    }

    private void setupTotalPrice() {
        double totalPrice = 0;
        for (int i = 0; i < productsAdapter.getData().size(); i++) {
            if (productsAdapter.getData().get(i).isSelected() && !StringUtil.isEmpty(productsAdapter.getData().get(i).getPrice())) {
                totalPrice += Double.parseDouble(productsAdapter.getData().get(i).getPrice()) * Integer.parseInt(productsAdapter.getData().get(i).getNumber());
            }
        }

        for (int i = 0; i < salonAdapter.getData().size(); i++) {
            if (salonAdapter.getData().get(i).isSelected() && !StringUtil.isEmpty(salonAdapter.getData().get(i).getPrice())) {
                totalPrice += Double.parseDouble(salonAdapter.getData().get(i).getPrice()) * Integer.parseInt(salonAdapter.getData().get(i).getNumber());
            }
        }
        mTotalPrice = totalPrice;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        totalPriceTv.setText(decimalFormat.format(mTotalPrice));
    }

    @Override
    public void getListSuccess(BaseResponse<ShoppingCarContent> response) {
//        View productHeader = getLayoutInflater().inflate(R.layout.shopping_car_item, productsRecycler, false);
//        View salonHeader = getLayoutInflater().inflate(R.layout.shopping_car_item, productsRecycler, false);
//        ((TextView) productHeader.findViewById(R.id.type_tv)).setText("商品");
//        ((TextView) salonHeader.findViewById(R.id.type_tv)).setText("沙龙");
        List<MultipleItem> multipleItemList = new ArrayList<>();
        if (response.getContent().getProductlist() != null && response.getContent().getProductlist().size() > 0) {
//            productsAdapter.addHeaderView(productHeader);
            MultipleItem item = new MultipleItem();
            item.setItemType(MultipleItem.productsList);
            multipleItemList.add(item);
            productsAdapter.setNewData(response.getContent().getProductlist());
            productsAdapter.notifyDataSetChanged();
        }

        if (response.getContent().getShalonglist() != null && response.getContent().getShalonglist().size() > 0) {
//            salonAdapter.addHeaderView(salonHeader);
            MultipleItem item = new MultipleItem();
            item.setItemType(MultipleItem.salonList);
            multipleItemList.add(item);
            salonAdapter.setNewData(response.getContent().getShalonglist());
            salonAdapter.notifyDataSetChanged();
        }
        multiAdapter.setNewData(multipleItemList);

    }

    @Override
    public void showLoading() {
        showProgressDialog("加载中...");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(this, msg);
    }


    private class ShoppingCarAdapter extends BaseQuickAdapter<ShoppingCarInfo> {

        public ShoppingCarAdapter(List<ShoppingCarInfo> list) {
            super(R.layout.shopping_car_products_item, list);

        }

        @Override
        protected void convert(final BaseViewHolder helper, final ShoppingCarInfo item) {
            if (isEditing) {
                helper.getView(R.id.info_layout).setVisibility(View.GONE);
                helper.getView(R.id.price_info).setVisibility(View.GONE);
                helper.getView(R.id.delete_layout).setVisibility(View.VISIBLE);
                helper.getView(R.id.number_picker_layout).setVisibility(View.VISIBLE);
            } else {
                helper.getView(R.id.info_layout).setVisibility(View.VISIBLE);
                helper.getView(R.id.price_info).setVisibility(View.VISIBLE);
                helper.getView(R.id.delete_layout).setVisibility(View.GONE);
                helper.getView(R.id.number_picker_layout).setVisibility(View.GONE);
            }

            helper.setText(R.id.title_tv, item.getTitle());
            helper.setText(R.id.price_tv, "￥" + item.getPrice());
            if (!StringUtil.isEmpty(item.getRemark())) {
                helper.setText(R.id.size_tv, item.getRemark());
            }
            helper.setText(R.id.num_tv, item.getNumber());
            if (item.isSelected()) {
                helper.setImageResource(R.id.checkbox, R.drawable.icon_checkbox_address_checked);
            } else {
                helper.setImageResource(R.id.checkbox, R.drawable.icon_checkbox_address_normal);
                isSelectall = false;
                selectAllIv.setImageResource(R.drawable.icon_checkbox_address_normal);
            }

            helper.getView(R.id.selected_layout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isSelected()) {
                        item.setSelected(false);
                    } else {
                        item.setSelected(true);
                    }
                    notifyDataSetChanged();

                    setupTotalPrice();
                }
            });


            PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhotourl()
                    , (ImageView) helper.getView(R.id.product_img_iv));

            final NumberPicker picker = helper.getView(R.id.number_picker);
            picker.setCurrentNum(Integer.parseInt(item.getNumber()));
            picker.setOnNumberPickerListener(new NumberPicker.OnNumberPickerListener() {
                @Override
                public void onPicker(final int num, int type) {
                    ShoppingCarControlPresenter presenter = new ShoppingCarControlPresenter(new ShoppingCarControlContract.View() {
                        @Override
                        public void onSuccess() {
                            item.setNumber(String.valueOf(num));
                        }

                        @Override
                        public void showLoading() {
                            helper.getView(R.id.number_progress).setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void hideLoading() {
                            helper.getView(R.id.number_progress).setVisibility(View.GONE);
                        }

                        @Override
                        public void onError(String code, String msg) {
                            T.showShort(mContext, msg);
                        }
                    });
                    presenter.updateNumber(item.getId(), String.valueOf(num));
//                    switch (type) {
//                        case _PickerAdd:
//                            presenter.addNumber(item.getId(), String.valueOf(num));
//
//                            break;
//                        case _PickerMinus:
//                            presenter.minusNumber(item.getId(), String.valueOf(num));
//                            break;
//                    }
                    picker.setCurrentNum(num);
                    setupTotalPrice();
                }

                @Override
                public void onFailed(int num, int maxNum) {

                }
            });
            helper.getView(R.id.delete_layout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showCustomAlertDialog("提示",
                            "您确定删除这一项吗"
                            , "取消"
                            , "删除"
                            , new CustomAlertDialog.CustomAlertDialogClickListener() {
                                @Override
                                public void onPositiveButtonClick() {
                                    hideDialog();
                                    ShoppingCarControlPresenter presenter = new ShoppingCarControlPresenter(new ShoppingCarControlContract.View() {
                                        @Override
                                        public void onSuccess() {
                                            remove(getData().indexOf(item));
                                            setupTotalPrice();
                                        }

                                        @Override
                                        public void showLoading() {
                                            showProgressDialog("正在删除，请稍候...");
                                        }

                                        @Override
                                        public void hideLoading() {
                                            hideDialog();
                                        }

                                        @Override
                                        public void onError(String code, String msg) {
                                            T.showShort(mContext, msg);
                                        }
                                    });
                                    presenter.deleteItem(item.getId());
                                }

                                @Override
                                public void onNegativeButtonClick() {
                                    hideLoading();
                                }
                            });
                }
            });
        }
    }

    private class MultiAdapter extends BaseMultiItemQuickAdapter<MultipleItem> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param context The context.
         * @param data    A new list is created out of this one to avoid mutable list
         */
        public MultiAdapter(Context context, List<MultipleItem> data) {
            super(data);
            addItemType(MultipleItem.productsList, R.layout.shoppingcar_product_list_layout);
            addItemType(MultipleItem.salonList, R.layout.shoppingcar_salon_list_layout);
        }

        @Override
        protected void convert(BaseViewHolder helper, MultipleItem item) {
            switch (helper.getItemViewType()) {
                case MultipleItem.productsList:
                    productsRecycler = helper.getView(R.id.products_recycler);
                    LinearLayoutManager layoutManager1 = new LinearLayoutManager(ShoppingCarActivity.this);
                    layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
                    productsRecycler.setLayoutManager(layoutManager1);

                    productsRecycler.setAdapter(productsAdapter);
                    break;

                case MultipleItem.salonList:
                    salonRecycler = helper.getView(R.id.salon_recycler);
                    LinearLayoutManager layoutManager2 = new LinearLayoutManager(ShoppingCarActivity.this);
                    layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
                    salonRecycler.setLayoutManager(layoutManager2);

                    salonRecycler.setAdapter(salonAdapter);
                    break;
            }


        }
    }
}
